from fastapi import APIRouter, HTTPException, Depends
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from apps.tab_manage.models import Group
from apps.tab_manage.response_model import GroupData
from common.response.response_schema import simple_response
from database.db_sql import get_db

router = APIRouter()


@router.post('')
async def add_group(group: GroupData, db: AsyncSession = Depends(get_db)):
    new_group = Group(name=group.name, sort_order=group.sort_order)
    async with db.begin():
        db.add(new_group)
    await db.commit()  # 提交事务
    await db.refresh(new_group)  # 在事务结束后再刷新
    return simple_response(code=201, data=new_group)


@router.put('/{group_id}')
async def update_group(group_id: int, group: GroupData, db: AsyncSession = Depends(get_db)):
    async with db.begin():
        existing_group = await db.execute(select(Group).where(Group.id == group_id))
        existing_group = existing_group.scalar_one_or_none()

        if not existing_group:
            return simple_response(code=404, msg='找不到分组')

        existing_group.name = group.name
        existing_group.sort_order = group.sort_order
        await db.commit()

    return simple_response(code=200, data=existing_group)


@router.get('')
async def get_groups(db: AsyncSession = Depends(get_db)):
    async with db.begin():
        result = await db.execute(select(Group).order_by(Group.sort_order, Group.id))
        groups = result.scalars().all()

    return simple_response(code=200, data=groups)


@router.delete('/{group_id}')
async def delete_group(group_id: int, db: AsyncSession = Depends(get_db)):
    async with db.begin():
        group = await db.execute(select(Group).where(Group.id == group_id))
        group = group.scalar_one_or_none()

        if not group:
            return simple_response(code=404, msg='找不到分组')

        await db.delete(group)
        await db.commit()

    return simple_response(code=204)
